<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>单例模式的弹框</title>
  <style>
    #modal{
      width: 200px;
      height: 200px;
      line-height: 200px;
      position: fixed;
      left: 50%;
      top: 50%;
      transform: translate(-50%, -50%);
      border: 1px solid #000;
      text-align: center;
    }
  </style>
</head>
<body>
  <button id="open">打开弹框</button>
  <button id="close">关闭弹框</button>

  <script>
    const Modal = (function() {
      let modal = null
      return function() {
        if (!modal) {
          modal = document.createElement('div')
          modal.innerHTML = '全局唯一的modal'
          modal.id = 'modal'
          modal.style.display = 'none'
          document.body.appendChild(modal)
        }
        return modal
      }
    })()

    document.getElementById('open').addEventListener('click', function() {
      const modal = new Modal()
      modal.style.display = 'block'
    })

    document.getElementById('close').addEventListener('click', function() {
      const modal = new Modal()
      if (modal) {
        modal.style.display = 'none'
      }
      
    })
  </script>
</body>
</html>